package com.llt.chatroom.controller;


import com.llt.chatroom.service.UserService;
import com.llt.chatroom.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Transactional(rollbackFor = {Exception.class})
public class UserController {

    @Resource
    private UserService userService;

//    实现登录接口
    @PostMapping ("/login")
    public Object login(String username, String password, HttpServletRequest request) {

        // 1. 先查询数据库里是否存在这个用户，找到后判断密码是否正确
        User user = userService.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            // 登录失败返回空对象
            return new User();
        }

        // 2. 登录成功，创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);

        // 3. 给前端返回 user
        log.info("登录成功: " + username);
        user.setPassword("");
        return user;
    }


//    实现注册接口
    @PostMapping("/register")
    public Object register(String username, String password) {

        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);

            int insert = userService.insert(user);
            log.info("注册: " + insert + "条");
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            // 名字重复抛出异常，注册失败
            user = new User();
            log.error("注册失败: " + username);
        }


        return user;
    }


//    获取登录信息
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req) {

        // 1. 先从请求中获取到 session
        HttpSession session = req.getSession(false);
        if (session == null) {
            log.error("未登录");
            return new User();
        }

        // 2. 在从会话中拿到 user
        User user = (User) session.getAttribute("user");
        if (user == null) {
            log.error("未知错误");
            return new User();
        }

        log.info("登录者：" + user.getUsername());

        // 3. 给客户端返回 user
        user.setPassword("");
        return user;
    }


















}
